package _interview100;

import java.util.Arrays;

/**
 * 64. 最小路径和
 */
public class No64 {
    private int[][] grid;
    private int[][] cache;

    public int minPathSum1(int[][] grid) {
        this.grid = grid;
        int m = grid.length;
        int n = grid[0].length;
        cache = new int[m][n];
        return dfs(m - 1, n - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0) return Integer.MAX_VALUE / 2;
        else if (cache[i][j] != 0) return cache[i][j];
        else if (i == 0 && j == 0) return cache[i][j] = grid[i][j];
        else return cache[i][j] = Math.min(dfs(i - 1, j), dfs(i, j - 1)) + grid[i][j];
    }

    public int minPathSum2(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] f = new int[m + 1][n + 1];
        Arrays.fill(f[0], Integer.MAX_VALUE / 2);
        for (int i = 0; i < m; i++) {
            f[i + 1][0] = Integer.MAX_VALUE / 2;
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) f[i + 1][j + 1] = grid[i][j];
                else f[i + 1][j + 1] = Math.min(f[i][j + 1], f[i + 1][j]) + grid[i][j];
            }
        }
        return f[m][n];
    }

    public int minPathSum4(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[] f = new int[n + 1];
        Arrays.fill(f, Integer.MAX_VALUE / 2);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) f[j + 1] = grid[i][j];
                else f[j + 1] = Math.min(f[j + 1], f[j]) + grid[i][j];
            }
        }
        return f[n];
    }
}
